const Service = require('egg').Service

class articleService extends Service {
  get Technology() {
    return this.ctx.model.Technology
  }
  get File() {
    return this.ctx.model.File
  }

  // 插入
  async insert(data) {
    const _data = await new this.Technology(data)
    _data.save()
    return _data
  }

  // 查询
  async getList(body) {
    const pageNum = Number.parseInt(body.pageNum || 1)
    const pageSize = Number.parseInt(body.pageSize || 10)
    const titleReg = new RegExp(body.title,'ig')
    const filterParams = {
      title: titleReg
    }
    const ret = await this.Technology.find(filterParams,null,{
      sort: {sortNum: -1}
    }).skip((pageNum-1)*pageSize).limit(pageSize).populate('img', 'link')
    const total = await this.Technology.countDocuments(filterParams)

    return {
      list: ret,
      total
    }
  }

  // 删除
  async delete(id) {
    const { service,ctx } = this
    const _data = await this.Technology.findById(id).populate('img')
    if(!_data) {
      ctx.throw('_id不正确！')
    }
    _data.remove()
    //删除文件
    if(_data.img) {
      await this.File.findByIdAndDelete(_data.img._id)
      service.toolService.deleteDiskFile(_data.img.link)
    }

    return {
      code: 200,
      message: '删除成功'
    }
  }

  // 修改
  async update(body) {
    const { ctx } = this
    const _data = await this.Technology.findByIdAndUpdate(body.id, Object.assign(body, {
      updatedAt: Date.now()
    }))
    if (!_data) {
      ctx.throw(422, '_id不正确')
    } 
    return {
      code: 200,
      message: '删除成功'
    }
  }
}

module.exports = articleService